package com.example.common.ui;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;


import com.example.common.R;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;

public abstract class BaseActivity extends AppCompatActivity {

    static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        // 全局背景色
        getWindow().getDecorView().setBackgroundColor(getBackgroundColor());

        // 状态栏
        setStatusBar();

        // 设置内容
        setContentView(getLayoutID());

        // 绑定黄油刀
        ButterKnife.bind(this);

        // 初始化行为
        initActions();

        // 初始化事件总线
        if (useEventBus()) {
            EventBus.getDefault().register(this);
        }
    }

    protected boolean useEventBus() {
        return false;
    }

    protected void setStatusBar() {}

    protected @ColorInt int getBackgroundColor(){
        return getResources().getColor(R.color.colorBackground);
    }

    public void startActivityAndFinish(Intent intent){
        startActivity(intent);
        finish();
    }

    public void finish(int resultCode) {
        setResult(resultCode);
        super.finish();
    }

    public void finish(int resultCode, Intent intent) {
        setResult(resultCode, intent);
        super.finish();
    }

    protected abstract @LayoutRes
    int getLayoutID();

    protected abstract void initActions();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        if (useEventBus()){
            EventBus.getDefault().unregister(this);
        }
    }
}
